package fi.jamk.ourcookingapp.activity;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import fi.jamk.ourcookingapp.R;
import fi.jamk.ourcookingapp.adapter.MyFriendAdapter;
import fi.jamk.ourcookingapp.backend.architecture.manager.ReceiptManager;
import fi.jamk.ourcookingapp.backend.exceptions.EmptySearchException;
import fi.jamk.ourcookingapp.backend.exceptions.NoUserException;
import fi.jamk.ourcookingapp.backend.model.User;

/**
 * Activity for showing the friend list
 * @author Marius
 */
public class FriendListActivity extends ListActivity implements OnScrollListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setBackgroundDrawableResource(R.drawable.bg);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		try {
			MyFriendAdapter adapter = new MyFriendAdapter(this, R.layout.list_item, AppActivity.facade.friendList());
			setListAdapter(adapter);
		} catch (InterruptedException | ExecutionException | JSONException | NoUserException e) {
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
		}
		getListView().setOnScrollListener(this);
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		User user = (User)getListAdapter().getItem(position);
		try {
			AppActivity.facade.setFilter(ReceiptManager.USER_ID, user.getID());
			AppActivity.tabHost.setCurrentTab(0);
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.userReceipts) + " " + user.getLoginName(), Toast.LENGTH_LONG).show();
			finish();
		} catch (EmptySearchException e) {
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	
	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
	}
	
}
